using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Toolkit.Services;

namespace Toolkit
{
    public class InputHandler : GameComponent, IInputHandler
    {
        Game game;
        private KeyboardState keyboardState;
        private GamePadState[] gamePads = new GamePadState[4];

#if !XBOX360
        private MouseState mouseState;
        private MouseState prevMouseState;
#endif

        #region Properties
        public KeyboardState KeyboardState
        {
            get { return keyboardState; }
        }

        public GamePadState[] GamePads
        {
            get { return gamePads; }
        }

#if !XBOX360
        public MouseState MouseState
        {
            get { return mouseState; }
        }

        public MouseState PreviousMouseState
        {
            get { return prevMouseState; }
        }
#endif
        #endregion

        public InputHandler(Game game)
            : base(game)
        {
            this.game = game;
            EnableInputHandler();

#if !XBOX360
            game.IsMouseVisible = true;
            prevMouseState = Mouse.GetState();
#endif
        }

        public override void Update(GameTime gameTime)
        {
            if (game.IsActive)
            {
                keyboardState = Keyboard.GetState();

                gamePads[0] = GamePad.GetState(PlayerIndex.One);
                gamePads[1] = GamePad.GetState(PlayerIndex.Two);
                gamePads[2] = GamePad.GetState(PlayerIndex.Three);
                gamePads[3] = GamePad.GetState(PlayerIndex.Four);

#if !XBOX360
                prevMouseState = mouseState;
                mouseState = Mouse.GetState();
#endif

                if (keyboardState.IsKeyDown(Keys.Escape)
                    || gamePads[0].Buttons.Back == ButtonState.Pressed)
                    Game.Exit();
            }
            base.Update(gameTime);
        }

        #region Public Methods
        public void EnableInputHandler()
        {
            this.Enabled = true;
            game.Services.AddService(typeof(IInputHandler), this);
        }

        public void DisableInputHandler()
        {
#if !XBOX360
            mouseState = new MouseState();
#endif
            keyboardState = new KeyboardState();

            for (int i = 0; i < gamePads.Length; i++)
                gamePads[i] = new GamePadState();

            this.Enabled = false;
        }
        #endregion
    }
}
